import json
from collections import defaultdict

import psycopg2


from collections import defaultdict

def merge_and_remove_multiple_states(sequence_json):
    indegree = defaultdict(set)
    outdegree = defaultdict(set)
    cond_map = defaultdict(list)
    param_map = defaultdict(list)
    edge_id_map = defaultdict(list)

    for row in sequence_json:
        u, v = row["now_state"], row["next_state"]
        indegree[v].add(u)
        outdegree[u].add(v)
        cond_map[(u, v)].append(row.get("condition", "无"))
        param_map[(u, v)].append(row.get("parameter", "无参数"))
        edge_id_map[(u, v)].append(row["id"])

    # 找需要删除的网关节点
    to_remove = []
    for node in set(indegree.keys()).union(outdegree.keys()):
        if "exclusiveGateway" in node or "parallelGateway" in node:
            to_remove.append(node)
    print("要删除的网关,", to_remove)
    new_rows = []
    for row in sequence_json:
        if row["now_state"] in to_remove or row["next_state"] in to_remove:
            continue
        new_rows.append(dict(row))

    # 合并
    for node in to_remove:
        preds = indegree[node]
        succs = outdegree[node]

        # 判断网关类型
        node_type = "parallel" if "parallelGateway" in node else "exclusive"
        for p in preds:
            for s in succs:
                print("处理节点对",p,"->",node,"->",s)
                if node_type == "parallel":
                    # 并行网关：条件恒为无
                    conds = ["无"]
                else:
                    if len(preds) > 1 and len(succs) == 1:
                        # 多入口单出口 → p→node 的条件
                        conds = cond_map.get((p, node), ["无"])
                        print("多入口单出口网关条件", conds)
                    elif len(preds) == 1 and len(succs) > 1:
                        # 单入口多出口 → node→s 的条件
                        conds = cond_map.get((node, s), ["无"])
                        print("单入口多出口网关条件", conds)
                    else:
                        conds = cond_map.get((p, node), ["无"])
                        print("其他网关条件", conds)
                        print(len(preds),len(succs))

                params = param_map.get((p, node), ["无参数"])
                ids = edge_id_map.get((node, s), [0])

                for i, cond in enumerate(conds):
                    param = params[0] if params else "无参数"
                    id = ids[i] if i < len(ids) else min(ids)
                    new_rows.append({
                        "id": id,
                        "now_state": p,
                        "next_state": s,
                        "condition": cond,
                        "parameter": param
                    })

    # 去重 + 重新编号
    new_rows = deduplicate_rows(new_rows)
    new_rows.sort(key=lambda x: x["id"] if x["id"] else 1e9)
    for idx, row in enumerate(new_rows, 1):
        row["id"] = idx

    return new_rows





def deduplicate_rows(sequence_json):
    """
    去除重复行（忽略 id 字段，仅比较其他字段是否一致）。

    Args:
        sequence_json (List[Dict]): 原始 JSON 列表

    Returns:
        List[Dict]: 去重后的 JSON 列表（保留第一条重复记录）
    """
    seen = set()
    deduplicated = []

    for row in sequence_json:
        # 构建去掉 id 的 row 作为比较依据
        row_without_id = {k: v for k, v in row.items() if k != "id"}
        row_tuple = tuple(sorted((k, str(v)) for k, v in row_without_id.items()))

        if row_tuple not in seen:
            seen.add(row_tuple)
            deduplicated.append(row)

    return deduplicated
# database = {
#     "dbname": "postgres",
#     "user": "postgres",
#     "password": "Rm15127373235*",
#     "host": "39.107.64.125",
#     "port": "5432"
# }
# conn = psycopg2.connect(**database)
# cursor = conn.cursor()
# cursor.execute("SELECT bpmn,json_sequence FROM bpmn_sequence WHERE workflow='初审'")
# bpmn_data,json_sequence=cursor.fetchone()
# json_sequence=json.loads(json_sequence)
# print(json_sequence)
# s=merge_and_remove_multiple_states(json_sequence)
# print(s)


